package com.smartcanteen.system.api.config;

import com.alibaba.fastjson2.JSONObject;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;

// 自定义错误解码器
public class FeignCustomErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        // 解析被调用方返回的错误信息
        String errorMessage = extractErrorMessage(response);
        return new RuntimeException(errorMessage); // 抛出自定义业务异常
    }

    private String extractErrorMessage(Response response) {
        try {
            String body = Util.toString(response.body().asReader());
            JSONObject json = new JSONObject(Integer.parseInt(body));
            return json.toString();
        } catch (Exception e) {
            return "服务调用异常";
        }
    }
}
